package com.power.config;

import cn.hutool.core.util.ObjectUtil;
import com.power.constant.AuthConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description feign拦截器,解决服务之间调用时，传递token问题
 * @Author dingchunlin
 * @Date 2024/07/12 15:16
 * @Version 1.0.0
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    /**
     * 实现RequestInterceptor接口的apply方法，在请求之前对请求模板进行设置
     * @param requestTemplate 请求模板
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取当前请求的上下文对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 判断是否有值
        if (ObjectUtil.isNotNull(requestAttributes)){
            // 获取请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            // 判断是否有值
            if (ObjectUtil.isNotNull(request)){
                // 获取token
                String token = request.getHeader(AuthConstants.AUTHORIZATION);
                requestTemplate.header(AuthConstants.AUTHORIZATION, token);
                return;
            }
        }
        // 不是浏览器发送的请求
        requestTemplate.header(AuthConstants.AUTHORIZATION, AuthConstants.BEARER + "674acb81-6def-445b-a667-c6375bb4607c");

    }
}
